package cn.kongwg.demo02;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author kongwg
 * @create 2021-05-27 8:15
 */
public class PDDemo {
    private AtomicInteger atomicInteger = new AtomicInteger();
    private BlockingQueue blockingQueue;
    private static boolean flag = true;

    public PDDemo(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void Produce() {
        System.out.println(Thread.currentThread().getName() + "\t 生产者启动");
        int data;
        boolean offer;
        while (flag) {
            data = atomicInteger.getAndIncrement();
            try {
                offer = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
                if (offer) {
                    System.out.println(Thread.currentThread().getName() + "\t 插入队列:" + data + "成功");
                } else {
                    System.out.println(Thread.currentThread().getName() + "\t 插入队列:" + data + "失败");

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public void consumer() {


        System.out.println(Thread.currentThread().getName() + "\t 消费者启动");
        Object retValue;
        while (flag) {
            try {
                retValue = blockingQueue.poll(2, TimeUnit.SECONDS);
                if (retValue != null) {
                    System.out.println(Thread.currentThread().getName() + "\t 消费队列:" + retValue + "成功");

                }else {
                    // FLAG = false;
                    System.out.println(Thread.currentThread().getName() + "\t 消费失败，队列中已为空，退出" );

                    // 退出消费队列
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 停止生产的判断
     */
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        PDDemo pdDemo = new PDDemo(new ArrayBlockingQueue(10));
        new Thread(() -> {
        pdDemo.Produce();
        }, "P").start();

        new Thread(() -> {
        pdDemo.consumer();
        }, "c").start();


         try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
         pdDemo.stop();
    }
}
